﻿using log4net;
using ServerControl.Model;
using System;
using System.Collections.Generic;
using System.Text;

namespace ServerControl.Dal
{
	public class FeedbackTypeDal : DbBase
	{
		private static ILog logger = LogManager.GetLogger("FeedbackTypeDal");
		private static List<FeedbackType> types = new List<FeedbackType>();

		public static List<FeedbackType> Types
		{
			get
			{
				if (types == null || types.Count == 0)
				{
					logger.Info("init types");
					types = Instance.Queryable<FeedbackType>().ToList();
				}

				return types;
			}
		}

		public static void ResetTypes()
		{
			logger.Info("reset types");
			types = Instance.Queryable<FeedbackType>().ToList();
		}

		/// <summary>
		/// 新增
		/// </summary>
		/// <param name="feedbackType"></param>
		/// <returns></returns>
		public static bool Insert(FeedbackType feedbackType)
		{
			var id = Instance.Insertable(feedbackType).ExecuteReturnIdentity();

			if (id > 0)
			{
				ResetTypes();
			}

			return id > 0;
		}

		public static bool Update(FeedbackType feedbackType)
		{
			var isSuccess = Instance
				.Updateable<FeedbackType>()
				.SetColumns(f => f.Name == feedbackType.Name)
				.Where(f => f.Id == feedbackType.Id && f.UserName == feedbackType.UserName)
				.ExecuteCommand() > 0;

			if (isSuccess)
			{
				ResetTypes();
			}

			return isSuccess;
		}

		/// <summary>
		/// 删除
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public static bool Delete(int id, string userName)
		{
			var isSuccess = Instance
					.Deleteable<FeedbackType>()
					.Where(g => g.Id == id && g.UserName == userName)
					.ExecuteCommand() > 0;

			if (isSuccess)
			{
				ResetTypes();
			}

			return isSuccess;
		}

		public static List<FeedbackType> Select(ref int records, int page, int limit, string userName, string name = "")
		{
			return Instance
				.Queryable<FeedbackType>()
				.Where(g => g.UserName == userName)
				.WhereIF(!string.IsNullOrEmpty(name), g => g.Name.Contains(name))
				.OrderBy(g => g.Id, SqlSugar.OrderByType.Desc)
				.ToPageList(page, limit, ref records);
		}
	}
}
